import request from '../../../utils/request';
import {
  searchFormIf,
  addForm,
  deleteReq,
  editForm,
  searchTree,
  searchPermisstionList,
  detailsSearch,
  findPlatform,
  findAll
} from '@/services/roleManageSer';
import {checkList}from '@/utils/utils'
import {
  message,
} from 'antd';


// 处理 页面型时使用
const getCheckKey = (checkData)=>{
  const checkKey = {};
  const halfCheckKey = {};
  for(let platform in checkData){
    const permisson = checkData[platform];
    if(permisson){
      let {checkKeyList ,halfCheckKeyList} =  getPermissId(permisson);
      checkKey[platform] = checkKeyList;
      halfCheckKey[platform] =halfCheckKeyList
    }
  }
  return {
    checked : checkKey,
    halfChecked : halfCheckKey
  }
}
const getPermissId =(permisson)=>{
  let checkKeyList = [];
  let halfCheckKeyList = [];

  permisson.map((item)=>{

      if(item.permissions && item.permissions.length>0){
        halfCheckKeyList.push(item.permission_id)
        //end=end.concat( this.state.halfCheckKey);

        const newCheckObj = getPermissId(item.permissions);
        checkKeyList =checkKeyList.concat (newCheckObj.checkKeyList);
        halfCheckKeyList = halfCheckKeyList.concat(newCheckObj.halfCheckKeyList);
      }else{
        checkKeyList.push(item.permission_id)
      }
  })
  return {
    checkKeyList : checkKeyList,
    halfCheckKeyList : halfCheckKeyList
  }
}

//处理 非页面型时使用
const getNoRoutePermissTree =(permissons) =>{
  const tree = []
  if(permissons && permissons.length>0){
    permissons.map((per,index)=>{
        if(per.permissions && per.permissions.length>0){ //说明有父菜单
            per.permission_name = per.permission_name+"-"+per.permissions[0].permission_name
            per.permissions = undefined;
            tree.push({
              ...per
            })
        }else {
          tree.push(per)
        }
    })
  }
  return tree;
}


export default {
  namepace: 'RoleManage',
  state: {
    pagination: {},
  },
  effects: {
    *selectBegin(payload, { call, put }) {
      const searchFormData = payload.payload;

      const data = yield call(searchFormIf, searchFormData);
      checkList(data.list);
      yield put({
        type: 'searchEnd',
        payload: {
          data: data,
          pagination: {
            page_size: data.page_size,
            total_pages: data.total_pages,
            page_num: data.page_num,
          },
          searchQ: searchFormData,
        },
      });
    },
    *addBegin({ payload, callback }, { call, put }) {
      const formData = payload.values;
      const addNow = yield call(addForm, formData);

      if (callback && typeof callback === 'function') {
        callback(addNow);
      }

      yield put({
        type: 'searchEnd',
      });
    },
    *findAll({ payload, callback }, { call, put }) {
      const data = yield call(findAll, payload);

      if (callback && typeof callback === 'function') {
        callback(data);
      }
      yield put({
        type: 'findAllEnd',
        payload: data,
      });
    },
    *deleteBegin({ payload, callback }, { call, put }) {
      const deleteNow = yield call(deleteReq, payload);
      if (callback && typeof callback === 'function') {
        callback (deleteNow);
      }
      yield put({
        type: 'searchEnd',
      });
    },
    *editBegin({ payload, callback }, { call, put }) {
      const editNow = yield call(editForm, payload);
      if(editNow){
        message.success('操作成功');
        return true;
      }
    },
    *detailsSearch({ payload, callback }, { call, put }) {
      const data = yield call(detailsSearch, payload);

      const response = yield call(findPlatform, payload);
      const checkData = {};
      const tabNameMap = {};
      if(response && response.return_code==='SUCCESS'){
        response.data.map((item)=>{
          tabNameMap[item.k] = item.v
        })
        data['tabNameMap'] = tabNameMap;
      }
      if(data && data.return_code==='SUCCESS'){
        for(let i  in data.platform_type){
          const platformCheckPermiss = yield call(searchTree, {platform_type : data.platform_type[i],role_id: payload.role_id});
          if (platformCheckPermiss && platformCheckPermiss.return_code === "SUCCESS") {
            checkData[data.platform_type[i]] =  platformCheckPermiss.data ;
          }
        }
      }

      data['checkData'] = checkData;

      if (callback && typeof callback === 'function') {
        callback(data);
      }

      yield put({
        type: 'detailsEnd',
        payload: data,
      });
    },
    *showUpdatePermssionModal({ payload }, { call, put }) {
       const response = yield call(findPlatform, payload); //查询字典
       const detailResponse = yield call(detailsSearch, {role_id: payload.role_id}); //查询角色详情
       const checkData = {};
       const platformPermissMap = {};
       const tabNameMap = {};
       if(response && response.return_code==='SUCCESS'){
         response.data.map((item)=>{ //生成 平台code对应 平台名称
           tabNameMap[item.k] = item.v
         })
       }
       if(detailResponse && detailResponse.return_code==='SUCCESS'){
          for(let i  in detailResponse.platform_type){//有几个平台就查几次
            const platformCheckPermiss = yield call(searchTree, {platform_type : detailResponse.platform_type[i],role_id: payload.role_id,is_left_menu:'1,4'}); //查询该角色的菜单
            if (platformCheckPermiss && platformCheckPermiss.return_code === "SUCCESS") {
                checkData[detailResponse.platform_type[i]] =  platformCheckPermiss.data ;

            }
            const platformPermiss = yield call(searchTree, {platform_type : detailResponse.platform_type[i],is_left_menu:'1,4'}); //查询所有的菜单
            if (platformPermiss && platformPermiss.return_code === "SUCCESS") {
              platformPermissMap[detailResponse.platform_type[i]] =  platformPermiss.data ;
            }
          }
       }
       const {checked ,halfChecked } = getCheckKey(checkData);//將所有選中角色 轉換成 半選中 和全選中兩種
      yield put({
        type: 'save',
        payload: {
          updateData : {
            updateRoleId : payload.role_id,
            tabNameMap:tabNameMap,
            checkPlatform : detailResponse.platform_type
          },
          platformData:response && response.return_code==='SUCCESS'?response.data:[],
          updateVisible : true,
          platformPermissMap:platformPermissMap,
          platformRoleMap:checked,
          platformHalfCheckMap:halfChecked //这个半选的值本来可以在树组件选中时自动生成，但用户没有操作树组件直接修改，获取不到父菜单id。为了防止这种情况加这个值初始化时使用
        }
      });


    },
    *showUpdateNoRoute ({ payload }, { call, put }){
      const response = yield call(findPlatform, payload); //查询字典
      const detailResponse = yield call(detailsSearch, {role_id: payload.role_id}); //查询角色详情
      const checkData = {};
      const platformPermissMap = {};
      const tabNameMap = {};
      if(response && response.return_code==='SUCCESS'){
        response.data.map((item)=>{ //生成 平台code对应 平台名称
          tabNameMap[item.k] = item.v
        })
      }
      if(detailResponse && detailResponse.return_code==='SUCCESS'){
        for(let i  in detailResponse.platform_type){//有几个平台就查几次
          const platformCheckPermiss = yield call(searchPermisstionList, {platform_type : detailResponse.platform_type[i],role_id: payload.role_id,is_left_menu:'2,3'}); //查询该角色的菜单
          if (platformCheckPermiss && platformCheckPermiss.return_code === "SUCCESS") {
            checkData[detailResponse.platform_type[i]] =  platformCheckPermiss.data.map((item)=>{ return item.permission_id}) ;

          }
          const platformPermiss = yield call(searchPermisstionList, {platform_type : detailResponse.platform_type[i],is_left_menu:'2,3'}); //查询所有的菜单
          if (platformPermiss && platformPermiss.return_code === "SUCCESS") {
            platformPermissMap[detailResponse.platform_type[i]] =  getNoRoutePermissTree(platformPermiss.data);
          }
        }
      }
      yield put({
        type: 'save',
        payload: {

          noRouteUpdateData : {
            updateRoleId : payload.role_id,
            tabNameMap:tabNameMap,
            checkPlatform : detailResponse.platform_type
          },
          noRoutePlatformData:response && response.return_code==='SUCCESS'?response.data:[],
          noRouteUpdateVisible : true,
          noRoutePlatformPermissMap:platformPermissMap,
          noRoutePlatformRoleMap:checkData,

        }
      });
    },
    *findPermissByPlatform({ payload }, { call, put }){  //platformType

      const platformPermissMap = {}
      if(payload.platformList && payload.platformList.length>0){
         const platformList = payload.platformList;
         for(let i =0; i<platformList.length ; i++){
           const response = yield call(searchTree, {platform_type : platformList[i],is_left_menu:'1,4'});
           if (response && response.return_code === "SUCCESS") {
             platformPermissMap[platformList[i]] =  response.data ;
           }
         }
      }
      yield put({
        type: 'save',
        payload: {
          platformPermissMap:platformPermissMap
        }
      });
    },
    *findNoRoutePermissByPlatform({ payload }, { call, put }){  //platformType

      const platformPermissMap = {}
      if(payload.platformList && payload.platformList.length>0){
        const platformList = payload.platformList;
        for(let i =0; i<platformList.length ; i++){
          const response = yield call(searchPermisstionList, {platform_type : platformList[i],is_left_menu:'2,3'});
          if (response && response.return_code === "SUCCESS") {
            platformPermissMap[platformList[i]] =  getNoRoutePermissTree(response.data) ;
          }
        }
      }
      yield put({
        type: 'save',
        payload: {
          noRoutePlatformPermissMap:platformPermissMap
        }
      });
    },

  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    searchEnd(state, { payload: payload }) {
      return {
        dataSource: payload,
      };
    },
    treeEnd(state, { payload: payload }) {
      return {
        permission: payload,
        ...state,
      };
    },
    //查询租户列表
    findAllEnd(state, { payload: payload }) {
      return {
        treeData: payload,
        ...state,
      };
    },
    detailsEnd(state, { payload: payload }) {
      return {
        detailsData: payload,
        ...state,
      };
    },
  },
};
